// DlgCheckOnline.cpp : implementation file
//

#include "stdafx.h"
#include "Celsus.h"
#include "DlgCheckOnline.h"
#include "DlgChangeLibrary.h"


// CDlgCheckOnline dialog

IMPLEMENT_DYNAMIC(CDlgCheckOnline, CDialog)

CDlgCheckOnline::CDlgCheckOnline(CWnd* pParent /*=NULL*/)
	: CDialog(CDlgCheckOnline::IDD, pParent)
	, m_szRequest(_T(""))
	, m_szUID(_T(""))
	, m_bSendLibrary(FALSE)
{
	m_nItemID = 0;
	m_nStaffID = 0;
}

CDlgCheckOnline::~CDlgCheckOnline()
{
}

void CDlgCheckOnline::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Text(pDX, IDC_EDIT_CITATION, m_szRequest);
	DDX_Control(pDX, IDC_EXPLORER, m_ctrlBrowser);
	DDX_Text(pDX, IDC_EDIT_ID, m_szUID);
	DDX_Check(pDX, IDC_CHECK_SEND_LIBRARY, m_bSendLibrary);
}


BEGIN_MESSAGE_MAP(CDlgCheckOnline, CDialog)
	ON_BN_CLICKED(IDC_BUTTON_RECHECK, &CDlgCheckOnline::OnBnClickedButtonRecheck)
	ON_EN_CHANGE(IDC_EDIT_ID, &CDlgCheckOnline::OnEnChangeEditId)
	ON_BN_CLICKED(IDC_BUTTON_PUBMED, &CDlgCheckOnline::OnBnClickedButtonPubmed)
END_MESSAGE_MAP()


BEGIN_EVENTSINK_MAP(CDlgCheckOnline, CDialog)
	ON_EVENT(CDlgCheckOnline, IDC_EXPLORER, 259, CDlgCheckOnline::DocumentCompleteExplorer, VTS_DISPATCH VTS_PVARIANT)
END_EVENTSINK_MAP()


// CDlgCheckOnline message handlers

BOOL CDlgCheckOnline::OnInitDialog()
{
	CDialog::OnInitDialog();

	ASSERT( m_nStaffID > -1 );
	ASSERT( m_nCurrentLibrary > -1 );
	ASSERT( m_pszaLibrary != NULL );

	// set URL
	CString szURL = appConfig.m_General.szSourceLink;

	// check for no file speicfied	
	if( szURL.IsEmpty() )
	{
		OnCancel();
	}
	// add ID
	szURL.Replace(_T("(UID)"), m_szUID );
	// navigate to show browser window
	m_ctrlBrowser.Navigate( szURL, NULL, NULL, NULL, NULL );

	// enable PUBMED
	if( !m_szUID.IsEmpty() && !appConfig.m_General.szPUBMEDLink.IsEmpty() )
		GetDlgItem( IDC_BUTTON_PUBMED )->EnableWindow();
	else if( appConfig.m_General.szPUBMEDLink.IsEmpty() )
		GetDlgItem( IDC_BUTTON_PUBMED )->ShowWindow( SW_HIDE );

	// update data
	UpdateData( FALSE );

	return TRUE;  // return TRUE unless you set the focus to a control
	// EXCEPTION: OCX Property Pages should return FALSE
}

void CDlgCheckOnline::OnOK()
{
	// update data
	UpdateData();

	// get source
	CString szPageSource;
	szPageSource = GetSource();
	// get title
	GetRequestTitle( szPageSource, &m_szTitle, &m_szSource );

	// update source
	if( !m_szSource.IsEmpty() )
	{
		// get request
		REQUEST_SET Request;
		appConfig.m_SQL.GetRequestSet( &Request, m_nItemID );

		// set variables
		Request.m_touched = TRUE;
		Request.m_webcheck = ID_CHECKED_ONLINE;

		// send to library
		if(m_bSendLibrary)
		{
			CDlgChangeLibrary dlgChange;
			// set variables
			dlgChange.m_nType = CDlgChangeLibrary::TYPE_SENDTO;
			dlgChange.m_nStaffID = m_nStaffID;
			dlgChange.m_nCurrentLibrary = Request.m_library_id;

			// show dialog
			if( dlgChange.DoModal() == IDCANCEL )
				return;

			// set new variables
			Request.m_library_id = dlgChange.m_nCurrentLibrary;
			Request.m_atlibrary = dlgChange.m_bIndicator;
			Request.m_redirected++;

			// set status
			if( !dlgChange.m_bRetainStatus )
			{
				Request.m_status_id = STATUS_ID_NEW;
				Request.m_touched = FALSE;
			}
		}

		// check title
		CString szTempFind = Request.m_request;
		CString szTemp = m_szTitle.Left( 10 );				
		szTemp.MakeLower();
		szTempFind.MakeLower();
		if( szTempFind.Find( szTemp ) == -1 )
		{
			// Ask if we want to add
			if( AfxMessageBox( IDS_ERROR_NO_TITLE_MATCH, MB_YESNO | MB_ICONEXCLAMATION ) == IDNO )
				return;
		}

		// trim source
		m_szSource.Trim();
		if( m_szSource.Left( 4 ).CompareNoCase( _T("the ") ) == 0 )
			m_szSource.Delete( 0, 4 );
		if( m_szSource.Left( 2 ).Compare( _T("A ") ) == 0 )
			m_szSource.Delete( 0, 2 );
		if( m_szSource.Left( 3 ).Compare( _T("An ") ) == 0 )
			m_szSource.Delete( 0, 3 );

		// set source and title variables
		Request.m_title = m_szTitle;
		Request.m_source = m_szSource;

		// set UID
		m_szUID = _T("ID:") + m_szUID;
		Request.m_uid = m_szUID;

		// set request
		appConfig.m_SQL.SetRequestSet( &Request );

		// write history
		CString szHistory;
		szHistory.Format( _T("Checked Online: Source Added UID=%s"), m_szUID );
		appConfig.UpdateRequestHistory( Request.m_id, m_nStaffID, Request.m_status_id, szHistory );

		// update data
		UpdateData( FALSE );
	}
	else
	{
		if( AfxMessageBox( _T("Unable to find source for request.\n\nDo you want to recheck?"), MB_YESNO ) == IDYES )
			return;
	}

	CDialog::OnOK();
}

void CDlgCheckOnline::OnCancel()
{
	// update request
	REQUEST_SET Request;
	appConfig.m_SQL.GetRequestSet( &Request, m_nItemID );
	// write history
	appConfig.UpdateRequestHistory( Request.m_id, m_nStaffID, Request.m_status_id, _T("Checked Online") );

	CDialog::OnCancel();
}

void CDlgCheckOnline::OnBnClickedButtonRecheck()
{
	// update data
	UpdateData();

	// disable ok button
	GetDlgItem( IDOK )->EnableWindow( FALSE );

	// set URL
	CString szURL = appConfig.m_General.szSourceLink;

	// check for no file speicfied	
	if( szURL.IsEmpty() )
	{
		OnCancel();
	}
	// add ID
	szURL.Replace(_T("(UID)"), m_szUID );
	// navigate to show browser window
	m_ctrlBrowser.Navigate( szURL, NULL, NULL, NULL, NULL );
}

void CDlgCheckOnline::OnBnClickedButtonPubmed()
{
	CString szURL;
	szURL = appConfig.m_General.szPUBMEDLink + m_szUID;
	// open window to URL
	ShellExecute( NULL, _T("open"), szURL, NULL, NULL, SW_SHOWNORMAL );	
}

void CDlgCheckOnline::OnEnChangeEditId()
{
	// set default button
	SetDefaultButton( IDC_BUTTON_RECHECK, FALSE );
}

CString CDlgCheckOnline::GetSource(void)
{
	CString szSource;
	HRESULT hr = S_FALSE;	
	IHTMLDocument2 *pDoc = NULL;

	// Load the current document into pDoc
	hr = m_ctrlBrowser.get_Document()->QueryInterface( IID_IHTMLDocument2, (void**)&pDoc );
	
	if( hr == S_OK )
	{
		BSTR pelementText = NULL;
		IHTMLElement *Element = NULL;
		// Get the body
		pDoc->get_body( &Element );
		
		Element->get_innerHTML( &pelementText );
		szSource = pelementText;
	} // End HTMLdocument is valid (HR == OK)

	return szSource;
}

void CDlgCheckOnline::DocumentCompleteExplorer(LPDISPATCH pDisp, VARIANT* URL)
{
	// set default button
	SetDefaultButton( IDOK );
}

BOOL CDlgCheckOnline::GetRequestTitle(CString szSource, CString *pszTitle, CString *pszSource)
{
	CString str = szSource;
	INT nStart = -1;
	INT nEnd = 0;

	// remove new lines
	str.Remove( '\n' );
	str.Remove( '\r' );

	// check for title (SFX)
	nStart = str.Find( appConfig.m_SFX.szTitleStartSearch );
	if( nStart != -1 )
	{
		nStart = str.Find( appConfig.m_SFX.szTitleMidSearch, nStart ) + (INT)_tcslen( appConfig.m_SFX.szTitleMidSearch );
		if( nStart != -1 )
		{
			nEnd = str.Find( appConfig.m_SFX.szTitleEndSearch, nStart );
			if( nEnd != -1 )
			{
				// get title
				*pszTitle = str.Mid( nStart, nEnd - nStart );
				// strip white space
				pszTitle->Trim();
				// normalize
				appConfig.NormalizeString( pszTitle );
			}
		}
	}

	// check for source (SFX)
	nStart = str.Find( appConfig.m_SFX.szSourceStartSearch );
	if( nStart != -1 )
	{
		nStart = str.Find( appConfig.m_SFX.szSourceMidSearch, nStart ) + (INT)_tcslen( appConfig.m_SFX.szSourceMidSearch );
		if( nStart != -1 )
		{
			nEnd = str.Find( appConfig.m_SFX.szSourceEndSearch, nStart );
			if( nEnd != -1 )
			{
				// get title
				*pszSource = str.Mid( nStart, nEnd - nStart );
				// strip white space
				pszSource->Trim();
				// normalize
				appConfig.NormalizeString( pszSource );
			}
		}
	}

	return TRUE;
}

INT CDlgCheckOnline::SetDefaultButton(const DWORD nNewId, BOOL bSetFocus) 
{
	// get previous deafult
	UINT nPrevId = GetDefID();

	// get previous window
	CWnd* pwndOld = GetDlgItem(nPrevId);
	if( pwndOld != NULL )
	{
		pwndOld->ModifyStyle( BS_DEFPUSHBUTTON, 0 );
	}

	// set as default
	SetDefID( nNewId );
	// get new window
	CWnd* pwndNew = GetDlgItem( nNewId );
	if( pwndNew != NULL )
	{
		pwndNew->EnableWindow();
		pwndNew->ModifyStyle( 0, BS_DEFPUSHBUTTON );
		if( bSetFocus )
			pwndNew->SetFocus();
	}

	// return previous
	return LOWORD(nPrevId);
}
